package com.wxlsoft.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.filechooser.FileFilter;

public class ExcelFileChooseListener implements ActionListener {

	private final JLabel label;
	private final JFileChooser chooser;
	
	public ExcelFileChooseListener(JLabel label, JFileChooser chooser) {
		this.label = label;
		this.chooser = new JFileChooser();
		this.chooser.setFileFilter(new FileFilter() {
			@Override
			public boolean accept(File file) {
				return file.isDirectory() || isExcel(file);
			}
			@Override
			public String getDescription() {
				return "*.xlsx (文本文件)";
			}
		});
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		chooser.setDialogType(JFileChooser.OPEN_DIALOG);
		// 显示文件打开的对话框
		int result = chooser.showOpenDialog(label.getParent());
		if (result == JFileChooser.APPROVE_OPTION) { 
			File file = chooser.getSelectedFile();
			if (!isExcel(file)) {
				ShowErrorMessage.show("文件格式错误");
				return;
			}
			label.setText(file.getAbsolutePath());
		}
	}

	public boolean isExcel(File file) {
		return file.getName().toLowerCase().endsWith(".xls") || 
				file.getName().toLowerCase().endsWith(".xlsx");
	}
	
}
